package com.wandian.texas.dao.Impl;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import com.wandian.texas.dao.TestDao;
import com.wandian.texas.db.DBMgr;
import com.wandian.texas.db.DbParameter;
import com.wandian.texas.db.WandianBaseDao;
import com.wandian.texas.entity.TestEntity;
import com.wandian.util.Log;

/**
 * @author long
 * @Create 2012-10-14 下午2:15:27
 * @QQ 108232706
 * @version 1.0
 * @description TestDaoImpl
 */
public class TestDaoImpl extends WandianBaseDao implements TestDao {

	public TestDaoImpl(DBMgr _dbMgr) {
		super(_dbMgr);
	}

//	@Override
//	protected Connection openConn()
//	{
//		return this.dbMgr.getDbWandian();
//	}

	public int AutoAddCount() {
		boolean result = false;
		String sql = " UPDATE t_test SET Count=Count+1 where Id=1 ";
		// Map<Integer, DbParameter> paraUpdate = new HashMap<Integer,
		// DbParameter>();
		result = execNoneQuery(sql) > -1;
		sql = "select * from t_test WHERE  Id=1;";
		PreparedStatement pstmt = this.execQuery(sql);
		ResultSet rs = null;
		int count = 0;
		if (pstmt != null) {
			try {
				rs = pstmt.executeQuery();
				if (rs.last()) {
					count = rs.getInt("Count");

				}
			} catch (SQLException e) {
				count = 0;
				Log.error("执行出错" + sql, e);
			} finally {
				closeConn(pstmt, rs);
			}
		}
		return count;
	}

	public int ReturnAutoAddCount() {
		String produceName = "sp_AutoAddNum";
		Map<Integer, DbParameter> paraUpdate = new HashMap<Integer, DbParameter>();
		paraUpdate.put(1, new DbParameter(4, 1));
//		paraUpdate.put(2, new DbParameter(Types.INTEGER));
		CallableStatement stmt = this.execProduce(produceName, paraUpdate);
		ResultSet rs = null;
		int count = 0;
		if (stmt != null) {
			try {
				boolean hasResultSet = stmt.execute(); //是否有结果集返回  	
				//				System.out.println("执行存储过程后Statement是否指向真正的结果集:" + hasResultSet);
				//				System.out.println("受影响的行数:" + stmt.getUpdateCount());
				//如果第一个结果是 ResultSet 对象
				if (hasResultSet) {
					rs = stmt.getResultSet();
					if (rs.last()) {
						count = rs.getInt("Count");
					}
				} else {
					while (stmt.getMoreResults())
					{
						rs = stmt.getResultSet();
						if (rs != null)
						{
							if (rs.last()) {
								count = rs.getInt("Count");
								break;
							}
						}
					}
				}
			} catch (SQLException e) {
				count = 0;
				Log.error("执行出错" + produceName, e);
			} finally {
				closeConn(stmt, rs);
			}
		}
		Log.debug(String.format("thread %s return %s", this.dbMgr.index, count));

		return count;
	}

	public TestEntity getTest(int id) {
		TestEntity info = null;
		return info;
	}
}
